<?php

namespace app\admin\model;

use Alipay\EasySDK\Kernel\Factory;
use Exception;
use think\exception\ValidateException;

/**
 * Order
 * @controllerUrl 'wechat'
 */
class Alipay
{
    protected function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';

        $options->appId = get_sys_config('app_id');

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = get_sys_config('app_secret_cert');

        $options->alipayCertPath = app()->getRootPath() . '/public' . get_sys_config('app_public_cert_path'); // alipayCertPublicKey_RSA2
        $options->alipayRootCertPath = app()->getRootPath() . '/public' . get_sys_config('alipay_root_cert_path'); // alipayRootCert
        $options->merchantCertPath = app()->getRootPath() . '/public' . get_sys_config('alipay_public_cert_path'); // appCertPublicKey_2021003161685475
        $options->notifyUrl = "https://greenoil.open258.top/index.php/api/alipay/paySuccess";

        return $options;
    }

    public function payment($payBody, $orderSn, $payPrice, $channel, $type)
    {
        Factory::setOptions($this->getOptions());
        $result = Factory::payment()->app()->pay($payBody, $orderSn, $payPrice);
        return $result->body;
    }

    /**
     * liuchao 2022/11/16
     * @param $orderId
     * @param $money
     * @throws Exception
     */
    public function refund($orderId, $money)
    {
        Factory::setOptions($this->getOptions());
        $result = Factory::payment()->common()->refund($orderId, $money);
//        $result = $result->httpBody;
//        $result = json_decode($result, true);
//        if(isset($result['alipay_trade_refund_response'])){
//            var_dump($result['alipay_trade_refund_response']);
//        }
//        die;
        if ($result->code != 10000) {
            throw new ValidateException($result->msg);
        }
    }

}